package com.bbs.crawl;

import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;

import com.bbs.bean.ReplyBBSOfPCAuto;
import com.bbs.dao.ReplyDaoOfPCAuto;
import com.car.util.DocUtil;
import com.car.util.Util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ReplyCrawlPCAuto implements Runnable {
	private int uid;
	private ReplyDaoOfPCAuto daoOfPCAuto;
	private static Logger logger = Logger.getLogger(ReplyCrawlPCAuto.class.getName());

	public ReplyCrawlPCAuto(int uid, ReplyDaoOfPCAuto daoOfPCAuto) {
		super();
		this.uid = uid;
		this.daoOfPCAuto = daoOfPCAuto;
	}

	public void run() {
		this.startParse(this.uid);
	}

	public void startParse(int uid) {
		logger.info(uid + "开始");
		for (int i = 1; i < 1000; i++) {
			String url = "http://bbs.pcauto.com.cn/intf/user/_posts.jsp?userId=" + uid
					+ "&maxLength=140&callback=show&pageSize=15&pageNo=" + i;
			Document doc = DocUtil.getDoc(url);
			if (doc.text().contains("error")
					|| Util.getMatched(doc.text(), "(\\[)(.{0,})(\\])").group(2).length() < 1) {
				break;
			}
			String res = Util.getMatched(doc.text(), "(\\[\\{)(.{0,})(\\}\\])").group(2);
			String[] s = res.split("\\},\\{");
			for (int j = 0; j < s.length; j++) {
				String obj = "[{" + s[j] + "}]";
				try {
					parseJson(obj);
				} catch (Exception e) {
					String reply = Util.getMatched(obj, "(\"title\":\")(.{0,})(\",\"topicAuthorId)").group(2);
					String ss = obj.replace(reply, reply.replaceAll("\"", ""));
					System.out.println(ss);
					String re = Util.getMatched(ss, "(\"content\":\")(.{0,})(\",\"fid)").group(2);
					String newObj = ss.replace(re, re.replaceAll("\"", ""));
					System.out.println(newObj.charAt(412));
					parseJson(newObj);
					continue;
				}
			}
		}
		logger.info(uid + "完成");
	}

	public void parseJson(String data) {
		JSONArray jsonarray = JSONArray.fromObject(data);
		for (int i = 0; i < jsonarray.size(); i++) {
			JSONObject job = jsonarray.getJSONObject(i);
			int hf_yhid = Integer.parseInt(job.get("authorId").toString());
			int hf_bbsid = Integer.parseInt(job.get("topicId").toString());
			String hf_bt = job.get("title").toString();
			String hf_nr = job.get("content").toString();
			int hf_uid = Integer.parseInt(job.get("topicAuthorId").toString());
			String hf_sj = "20" + job.get("lastPostAt").toString();
			ReplyBBSOfPCAuto rep = new ReplyBBSOfPCAuto(hf_yhid, hf_bbsid, hf_bt, hf_nr, hf_uid, hf_sj);
			daoOfPCAuto.insertReply(rep);
		}
	}

}
